﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using HS.RealEstate.RabbitMQ;
using Logistics.Commn;
using Logistics.SignIn;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Logistics.Web.Controllers
{
    public class LoginController : Controller
    {
        readonly ISignInAppService _signInAppService;

        public LoginController(ISignInAppService signInAppService)
        {
            _signInAppService = signInAppService;
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="accountNumber">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public int DoLogin(string accountNumber, string password)
        {
            var i = _signInAppService.PostSignEfInAsync(accountNumber, password).Result;
            return i;
        }

        /// <summary>
        /// 忘记密码视图
        /// </summary>
        /// <returns></returns>
        public IActionResult ForgetPasswordView()
        {
            return View();
        }

        /// <summary>
        /// 验证用户名是否存在
        /// </summary>
        /// <param name="accountNumber"></param>
        /// <returns></returns>
        public int PostVerifyWhetherTheAccountExists(string accountNumber)
        {
            int i = _signInAppService.VerifyAccountNumber(accountNumber).Result;
            return i;
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        public void GetSendMail(string box)
        {
            _signInAppService.SendMailbox(box);
        }

        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public int Verification(string code)
        {
            if (code.ToUpper() == RedisHelper.Get("randomNumber").ToUpper())
            {
                return 1;
            }

            return 0;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public int PutChangePassword(string accountNumber, string password)
        {
            int i = _signInAppService.PutChangePassword(accountNumber, password).Result;
            return i;
        }

        /// <summary>
        /// 人脸识别视图
        /// </summary>
        /// <returns></returns>
        public ActionResult FaceIndex()
        {
            return View();
        }

        /// <summary>
        /// 人脸识别
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public JsonResult PostFaceDistinguish(string image)
        {
            // 设置APPID/AK/SK
            var API_KEY = "KbPRzrOdy4pVgTeSKvnLSHUj"; //你的 Api Key
            var SECRET_KEY = "ZE9An2EZbqKQlkUPgmFnpfkE3roaMjs8"; //你的 Secret Key
            var client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY)
            {
                Timeout = 60000 // 修改超时时间
            };

            var imageType = "BASE64"; //BASE64   URL
            string imgData64 = image;
            imgData64 = imgData64.Substring(imgData64.IndexOf(",", StringComparison.Ordinal) + 1); //将‘，’以前的多余字符串删除

            ResultInfo result = new ResultInfo();
            try
            {
                var groupId = "group1";
                var userId = "user1";
                var result323 = client.Detect(imgData64, imageType);
                ////活体判断
                var faces = new JArray
                {
                    new JObject
                    {
                        { "image", imgData64 },
                        { "image_type", "BASE64" }
                    }
                };
                var living = client.Faceverify(faces); //活体检测交互返回
                var livingJson = Newtonsoft.Json.JsonConvert.SerializeObject(living);
                if (Newtonsoft.Json.JsonConvert.DeserializeObject(livingJson) is JObject livingObj && livingObj["error_code"]?.ToString() == "0" && livingObj["error_msg"]?.ToString() == "SUCCESS")
                {
                    var livingResult =
                        Newtonsoft.Json.JsonConvert.DeserializeObject(livingObj["result"]?.ToString() ?? string.Empty) as JObject;
                    if (livingResult != null)
                    {
                        var livingList = livingResult["thresholds"];
                        double faceLiveness = Convert.ToDouble(livingResult["face_liveness"]);
                        if (livingList != null)
                        {
                            var frr = Newtonsoft.Json.JsonConvert.SerializeObject(livingList.ToString());
                        }

                        if (livingList != null)
                        {
                            var frr1EObj = Newtonsoft.Json.JsonConvert.DeserializeObject(livingList.ToString()) as JObject;
                            if (frr1EObj != null)
                            {
                                double frr1E4 = Convert.ToDouble(frr1EObj["frr_1e-4"]);
                                if (faceLiveness < frr1E4)
                                {
                                    result.Info = "识别失败：不是活体！";
                                    return Json(result);
                                }
                            }
                        }
                    }
                }

                //首先查询是否存在人脸
                var result2 = client.Search(imgData64, imageType, groupId);
                var strJson = Newtonsoft.Json.JsonConvert.SerializeObject(result2);
                var o2 = Newtonsoft.Json.JsonConvert.DeserializeObject(strJson) as JObject;


                //判断是否存在当前人脸，相识度是否大于80
                if (o2 != null && o2["error_code"]?.ToString() == "0" && o2["error_msg"]?.ToString() == "SUCCESS")
                {
                    var resultList = Newtonsoft.Json.JsonConvert.DeserializeObject(o2["result"]?.ToString() ?? string.Empty) as JObject;
                    if (resultList != null)
                    {
                        var userList = resultList["user_list"];
                        if (userList != null)
                        {
                            var obj = JArray.Parse(userList.ToString());
                            foreach (var item in obj)
                            {
                                //80分以上可以判断为同一人，此分值对应万分之一误识率
                                var score = Convert.ToInt32(item["score"]);
                                if (score > 80)
                                {
                                    result.Info = result2.ToString();
                                    result.Res = true;
                                    result.Startcode = 221;
                                    return Json(result);
                                }
                            }
                        }
                    }
                }
                else
                {
                    result.Info = strJson.ToString();
                    result.Res = false;
                    return Json(result);
                }
            }
            catch (Exception e)
            {
                result.Info = e.Message;
            }

            return Json(result);
        }

        /// <summary>
        /// 定义一个返回类型的实体
        /// </summary>
        public class ResultInfo
        {
            public ResultInfo()
            {
                //默认值
                Res = false;
                Startcode = 449;
                Info = "";
                Other = "";
            }
            public bool Res { get; set; } //返回状态（true or false）
            public int Startcode { get; set; } //返回http状态码
            public string Info { get; set; } //返回结果
            public string Other { get; set; } //其他
        }
    }
}